package com.arnojin.oschina.api.util;

import java.util.concurrent.ThreadLocalRandom;

/**
 * MathUtil
 *
 * @author arno
 * @date 2021/01/26 21:19
 */
public class MathUtil {
    public MathUtil() {
    }

    public static int parseDigit(char digit) {
        if (digit >= '0' && digit <= '9') {
            return digit - 48;
        } else {
            return CharUtil.isLowercaseAlpha(digit) ? 10 + digit - 97 : 10 + digit - 65;
        }
    }

    public static long randomLong(long min, long max) {
        return min + (long) (ThreadLocalRandom.current().nextDouble() * (double) (max - min));
    }

    public static int randomInt(int min, int max) {
        return min + (int) (ThreadLocalRandom.current().nextDouble() * (double) (max - min));
    }

    public static boolean isEven(int x) {
        return x % 2 == 0;
    }

    public static boolean isOdd(int x) {
        return x % 2 != 0;
    }

    public static String humanReadableByteCount(long bytes, boolean useSi) {
        int unit = useSi ? 1000 : 1024;
        if (bytes < (long) unit) {
            return bytes + " B";
        } else {
            int exp = (int) (Math.log((double) bytes) / Math.log((double) unit));
            String pre = (useSi ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (useSi ? "" : "i");
            return String.format("%.1f %sB", (double) bytes / Math.pow((double) unit, (double) exp), pre);
        }
    }
}